import preact from "@preact/preset-vite"
import { execSync } from "child_process"
import path, { resolve } from "path"
import { CommonServerOptions, defineConfig, loadEnv } from "vite"
import svgr from "vite-plugin-svgr"
// @ts-ignore
import { vanillaExtractPlugin } from "@vanilla-extract/vite-plugin"
import legacy from "@vitejs/plugin-legacy"
import compression from "vite-plugin-compression"
// @ts-ignore
import eslint from "vite-plugin-eslint"
import imagemin from "vite-plugin-imagemin"

// 獲取 git commit hash 作為版本號
const __APP_VERSION__ = (() => {
    const _hash = execSync("git rev-parse --short HEAD").toString().trim()
    return JSON.stringify(_hash)
})()

// @ts-ignore
// https://vite.dev/config/
export default defineConfig(async (config) => {
    const env = loadEnv(config.mode, resolve(__dirname), "APP") as ViteConfigEnv
    // 輸出構建信息
    console.info("转案版本：", __APP_VERSION__)
    console.info("专案路径：", __dirname)
    console.info("构建模式：", config.mode)
    console.info("构建组态：", config)
    console.info("环境变量：", env)

    const proxy: CommonServerOptions["proxy"] = {
        "/api/v1": {
            target: `${env.APP_API_REF_BASE_URL}:1080`,
            changeOrigin: true,
            secure: false,
        },
        "/api/v2": {
            target: `${env.APP_API_REF_BASE_URL}:7093`,
            changeOrigin: true,
            secure: false,
            rewrite: (path) => path.replace(/^\/api\/v2/, ""),
        },
        "/ocr": {
            target: `${env.APP_API_REF_BASE_URL}:7093`,
            changeOrigin: true,
            secure: false,
        },
        "/member": {
            target: `${env.APP_API_REF_BASE_URL}:7093`,
            changeOrigin: true,
            secure: false,
        },
        "/finance": {
            target: `${env.APP_API_REF_BASE_URL_TEST}:80`,
            changeOrigin: true,
            secure: false,
        },
        "/game": {
            target: `${env.APP_API_REF_BASE_URL_TEST}:80`,
            changeOrigin: true,
            secure: false,
        },
    }

    console.info("代理配置：", proxy)

    return {
        plugins: [
            vanillaExtractPlugin(),
            preact({
                jsxImportSource: "@emotion/react",
                babel: {
                    plugins: [
                        [
                            "@emotion/babel-plugin",
                            {
                                sourceMap: true,
                                autoLabel: "dev-only",
                                labelFormat: "[local]",
                                cssPropOptimization: true,
                            },
                        ],
                        [
                            "babel-plugin-styled-components",
                            {
                                pure: true,
                                displayName: true,
                                fileName: true,
                            },
                        ],
                    ],
                },
            }),
            eslint(),
            svgr(),
            // imagemin({
            //     gifsicle: { optimizationLevel: 7, interlaced: false },
            //     mozjpeg: { quality: 60, progressive: true },
            //     pngquant: { quality: [0.6, 0.7], speed: 4 },
            //     svgo: { plugins: [{ name: "removeViewBox", active: false }] },
            //     webp: { quality: 70 },
            // }),
            // compression({
            //     algorithm: "gzip",
            //     ext: ".gz",
            //     threshold: 10240,
            // }),
            // compression({
            //     algorithm: "brotliCompress",
            //     ext: ".br",
            //     threshold: 10240,
            // }),
            // legacy({
            //     targets: ["defaults", "not IE 11", "Android >= 6", "iOS >= 10.3"],
            //     additionalLegacyPolyfills: [
            //         "regenerator-runtime/runtime",
            //         "core-js/features/array/find",
            //         "core-js/features/promise",
            //     ],
            //     polyfills: true,
            // }),
        ],
        optimizeDeps: {
            esbuildOptions: {
                target: "es2020",
            },
        },
        esbuild: {
            logOverride: { "this-is-undefined-in-esm": "silent" },
        },
        resolve: {
            alias: {
                "@": path.resolve(__dirname, "./src"),

                // preact 開關
                react: "preact/compat",
                "react-dom/test-utils": "preact/test-utils",
                "react-dom": "preact/compat",
                "react/jsx-runtime": "preact/jsx-runtime",
            },
        },
        publicDir: "public",
        define: {
            __APP_VERSION__,
            __APP_API_V1_BASE_URL__: JSON.stringify(env.__APP_API_V1_BASE_URL__),
        },
        assetsInclude: [
            "**/*.md",
            "**/*.png",
            "**/*.jpg",
            "**/*.jpeg",
            "**/*.svg",
            "**/*.gif",
            "**/*.webp",
            "**/*.ico",
            "**/*.woff",
            "**/*.woff2",
            "**/*.ttf",
            "**/*.eot",
            "**/*.otf",
            "**/*.svg",
            "**/*.json",
            "**/*.pag",
        ],
        server: {
            port: 38881,
            host: "0.0.0.0",
            proxy,
            allowedHosts: ["fluent-seriously-ferret.ngrok-free.app"],
        },
        preview: {
            port: 38882,
            host: "0.0.0.0",
            proxy,
            allowedHosts: ["fluent-seriously-ferret.ngrok-free.app"],
        },
        build: {
            outDir: "dist",
            assetsInlineLimit: 4096,
            minify: "esbuild",
            esbuildOptions: {
                treeShaking: true,
            },
            terserOptions: {
                maxWorkers: 10,
                compress: {
                    drop_console: true,
                    drop_debugger: true,
                    pure_funcs: ["console.log", "console.debug"],
                },
            },
            chunkSizeWarningLimit: 1024,
            target: [
                // "es2015",
                // "safari11",
                // "chrome60",
                // "firefox60",
                // "edge18",
                // "ios11",
                // "android4.4",
            ],
            cssTarget: ["chrome60", "safari11", "ios11"],
            commonjsOptions: {
                include: [/node_modules/],
            },
            sourcemap: true,
            rollupOptions: {
                preserveEntrySignatures: "strict",
                preserveSymlinks: true,
                output: {
                    chunkFileNames: (chunkInfo: { name: string }) => {
                        // @ts-ignore
                        if (chunkInfo.name.startsWith("preload_")) {
                            return `chunks/${chunkInfo.name}.js`
                        }
                        return `chunks/${chunkInfo.name}.[hash].js`
                    },
                    manualChunks(id: string) {
                        // 其他依賴處理...
                        if (id.includes("node_modules")) {
                            if (id.includes("preact")) return "preload_vendor_preact"

                            if (id.includes("jotai") || id.includes("zustand"))
                                return "vendor_state"

                            if (id.includes("@emotion") || id.includes("styled-components"))
                                return "vendor_styling"

                            if (id.includes("lodash")) return "vendor_utils"

                            return "vendors"
                        }
                    },
                },
            },
        },
    }
})
